package auth;

import apirequest.ApiRequest;
import storage.CredentialStorage;
import storage.MySqlCredentialStorage;
import token.AuthToken;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liangyaqian
 */
public class DefaultApiAuthencatorImpl implements ApiAuthencator {

    private CredentialStorage credentialStorage;

    public DefaultApiAuthencatorImpl() {
        credentialStorage = new MySqlCredentialStorage();
    }

    @Override
    public void auth(String url)
    {
        ApiRequest apiRequest = ApiRequest.buildFromUrl(url);
        auth(apiRequest);
    }

    @Override
    public void auth(ApiRequest apiRequest)
    {
        String appId = apiRequest.getAppId();
        String token = apiRequest.getToken();
        long timestamp = apiRequest.getTimeStamp();
        String baseUrl = apiRequest.getBaseUrl();
        AuthToken clientAuthToken = new AuthToken(timestamp,token);
        // 根据时间戳判断 token 是否过期失效
        if (clientAuthToken.isExpired()) {
            throw new RuntimeException("Token is expired.");
        }

        String password = credentialStorage.getPasswordByAppId(appId);
        AuthToken serverAuthToken = AuthToken.create(baseUrl, appId, timestamp, password);
        // 验证两个 token 是否匹配
        if (!serverAuthToken.match(clientAuthToken))
        {
            throw new RuntimeException("Token verfication failed.");
        }
        System.out.println("鉴权通过");
    }
}
